<?php

namespace app\common\services;

use app\common\model\Answer;
use app\common\model\CourseQuestion;
use app\common\model\Rate;

class AnswerService
{
    public static function setAnswer($course_id,$user_id,$questions)
    {
        $an = Answer::where('day',date('Y-m-d'))->where('user_id',$user_id)->find();
        if($an){
            Answer::where('day',date('Y-m-d'))->where('user_id',$user_id)->inc('answernum',count($questions))->update(['updatetime'=>time()]);
        }else{
            Answer::insert([
                'user_id'=>$user_id,
                'day'=>date('Y-m-d'),
                'answernum'=>count($questions),
                'createtime'=>time(),
                'updatetime'=>time()
            ]);
        }
        $cate = $course_id;
        $course_id = CourseQuestion::where('cate_id',$cate)->value('course_id');
        if(!$course_id){
            return false;
        }
        $d = Rate::where('user_id',$user_id)->where('course_id',$course_id)->find();
        $total = CourseQuestion::where('course_id',$course_id)->count();
        if($d){
            self::updateRate($d,$user_id,$course_id,$total,$questions);
        }else{
            $d = Rate::create(['user_id'=>$user_id,'course_id'=>$course_id,'cate_id'=>$cate]);

            if($total == 1){
                self::updateRate($d,$user_id,$course_id,$total,$questions);
            }
        }
    }

    public static function updateRate($d,$user_id,$course_id,$total,$questions)
    {
        $content = false;
        if($d['course_content']){
            $ar = explode(',',$d['course_content']);
            foreach ($questions as $v){
                if(!in_array($v['id'],$ar)){
                    $content = $d['course_content'].','.$v['id'];
                }
            }
            $usercount = count($ar) + count($questions);
            $rate = $total ? round($usercount / $total * 100,0) : 0;
        }else{
            $content = implode(',',array_column($questions,'id'));
            $usercount = count($questions);
            $rate = $total ? round($usercount / $total * 100,0) : 0;
        }

        if($content){
            $update['course_content'] = $content;
            $update['rate'] = $rate;
            $update['total'] = $total;
            Rate::where('user_id',$user_id)->where('course_id',$course_id)->update($update);
        }
    }

    public static function setDuration($course_id,$user_id)
    {
        $cate = $course_id;
        $course_id = CourseQuestion::where('cate_id',$cate)->value('course_id');
        $d = Rate::where('user_id',$user_id)->where('course_id',$course_id)->find();
        if($d){
            Rate::where('user_id',$user_id)->where('course_id',$course_id)->inc('duration')->update();
        }else{
            Rate::create(['duration'=>1,'user_id'=>$user_id,'course_id'=>$course_id,'cate_id'=>$cate]);
        }
    }
}